package freespiritsocial.io.user.ui.fragment.account

import android.content.Intent
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.core.os.bundleOf
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.databinding.FrgSignUpSup1Binding
import freespiritsocial.io.user.ext.goMain
import freespiritsocial.io.user.handle.BackHandle
import freespiritsocial.io.user.ui.activity.MainAct
import freespiritsocial.io.user.ui.activity.WebActivity
import freespiritsocial.io.user.util.CacheUtil
import freespiritsocial.io.user.viewmodel.SignUpModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction

class SignSup1UpFrg: BaseFragment<SignUpModel,FrgSignUpSup1Binding>() {

    override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
        //设置view model作用域
        viewModelOwner = (activity as MainAct).accountViewModelOwner
        super.onViewCreated(view,savedInstanceState)
    }

    override fun layoutId(): Int = R.layout.frg_sign_up_sup1

    val act by lazy {
        activity as MainAct
    }

    private fun initFacebook() {
        LoginManager.getInstance()
            .registerCallback(act.callbackManager,object: FacebookCallback<LoginResult> {
                override fun onSuccess(result: LoginResult?) {
                    if (isHidden) return
                    result?.accessToken?.userId?.let { userid ->
                        mViewModel.faceBook(userid,{
                            nav().navigateAction(R.id.signSup2UpFrg,bundleOf("thirdPartyType" to 3,SignSup2UpFrg.key_third_name to userid))
                        },{
                            CacheUtil.token = it
                            nav().goMain()
                        })
                    }
                    LoginManager.getInstance().logOut()
                }

                override fun onCancel() {
                }

                override fun onError(error: FacebookException?) {
                    mViewModel.toast.postValue(error?.message)
                }
            })

    }

    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.countryCode.set(mDatabind.includedPhone.ccp.selectedCountryCodeWithPlus)
        mDatabind.viewModel = mViewModel
        mDatabind.click = Click()
        mDatabind.tvProtocol.movementMethod = LinkMovementMethod.getInstance()
        mDatabind.tvProtocol.highlightColor = requireContext().getColor(R.color.picture_color_transparent)
        mDatabind.tvProtocol.text = protocol()
        initCcp()
    }

    private fun initCcp() {
//        mDatabind.includedPhone.ccp.registerCarrierNumberEditText(mDatabind.includedPhone.etPhoneNumber)
        mDatabind.includedPhone.ccp.setOnCountryChangeListener {
            mViewModel.countryCode.set(mDatabind.includedPhone.ccp.selectedCountryCodeWithPlus)
        }
    }

    override fun onDestroyView() {
        LoginManager.getInstance().unregisterCallback(act.callbackManager)
        viewModelOwner?.viewModelStore?.clear()
        super.onDestroyView()
    }

    private fun protocol() = SpannableStringBuilder().apply {
        append("By tapping ’Next’ , I agree with ")
        var start = length
        append("Terms of \nUse",ForegroundColorSpan(0xff12161E.toInt()),Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        setSpan(object: ClickableSpan() {
            override fun onClick(widget: View) {
                openBrowser("Terms of Use","https://www.freespiritapp.com/terms-and-conditions")
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.isUnderlineText = false
                ds.color = requireContext().getColor(R.color.T1)
                ds.linkColor = requireContext().getColor(R.color.T1)
            }
        },start,length,0)
        append(" and ",ForegroundColorSpan(0xff6C778B.toInt()),Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        start = length
        append("Privacy Policy",ForegroundColorSpan(0xff12161E.toInt()),Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        setSpan(object: ClickableSpan() {
            override fun onClick(widget: View) {
                openBrowser("Privacy Policy","https://www.freespiritapp.com/privacy-policy")
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.isUnderlineText = false
                ds.color = requireContext().getColor(R.color.T1)
                ds.linkColor = requireContext().getColor(R.color.T1)
            }
        },start,length,0)
    }

    fun openBrowser(title: String,url: String) {
        WebActivity.launch(requireContext(),title,url)
    }


    var client: GoogleSignInClient? = null

    override fun onActivityResult(requestCode: Int,resultCode: Int,data: Intent?) {
        if (requestCode == LoginFrg.RC_SIGN_IN) {
            GoogleSignIn.getSignedInAccountFromIntent(data).runCatching {
                getResult(ApiException::class.java)
            }.onSuccess {
                mViewModel.google(it.id ?: "",{
                    nav().navigateAction(R.id.signSup2UpFrg,bundleOf("thirdPartyType" to 2,SignSup2UpFrg.key_third_name to it.id))
                },{
                    CacheUtil.token = it
                    nav().goMain()
                })
                client?.signOut()
            }
        }
        super.onActivityResult(requestCode,resultCode,data)
    }

    inner class Click: BackHandle {
        fun next() {
            mViewModel.checkMobile {
                nav().navigateAction(R.id.action_signUpFrg_to_verificationCodeFrg)
            }
        }

        fun signUpWithGoogle() {
            val gso =
                GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestId()
                    .build()
            client = GoogleSignIn.getClient(requireContext(),gso)
            val signInIntent: Intent? = client?.signInIntent
            startActivityForResult(signInIntent,LoginFrg.RC_SIGN_IN)
        }

        fun signUpWithFacebook() {
            initFacebook()
            LoginManager.getInstance()
                .logInWithReadPermissions(
                    act,
                    listOf("public_profile","email")
                )
        }

        override fun goBack() {
            nav().navigateUp()
        }
    }
}